package cn.com.main;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Set;
import java.util.TreeSet;

public class HarParser {
    public static void main(String[] args) {
        String harFilePath = "E:\\cloud_star\\240911东莞大模型项目\\test.har";
        Set<String> urls = parsingHarFile(harFilePath);
        urls.forEach(url -> System.out.println(url));
    }

    /**
     * 获取网址
     * 解析har文件，获取所有请求的url，并去除参数
     *
     * @param harFilePath har文件路径
     * @return {@link Set }<{@link String }>
     */
    public static Set<String> parsingHarFile(String harFilePath) {
        Set<String> urls = new TreeSet<>();
        try {
            String content = new String(Files.readAllBytes(Paths.get(harFilePath)));
            JSONObject har = new JSONObject(content);
            JSONArray entries = har.getJSONObject("log").getJSONArray("entries");
            for (int i = 0; i < entries.size(); i++) {
                JSONObject entry = entries.getJSONObject(i);
                JSONObject request = entry.getJSONObject("request");
                String str = request.getStr("url");
                int endIndex = str.indexOf("?");
                String url = str.substring(0, endIndex > 0 ? endIndex : str.length());
                urls.add(url + "\t" + request.getStr("method"));
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return urls;
    }
}